package com.leo;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.Objects;

/**
 * @ClassName SystemTrayDemo
 * @Description
 * @Author wangss
 * @date 2020.11.12 17:22
 * @Version 1.0
 */
public class SystemTrayDemo2 extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {

        // 剩最后一个窗口时是否关闭程序，true是关闭，false是不关闭
        Platform.setImplicitExit(false);

        AnchorPane pane = new AnchorPane();

        AnchorPane root = new AnchorPane();

        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.setWidth(1000);
        primaryStage.setHeight(500);
        primaryStage.centerOnScreen();
        primaryStage.setTitle("系统托盘");
        primaryStage.show();

        URL url = this.getClass().getClassLoader().getResource("sound/1.mp3");
        Media media = new Media(url.toExternalForm());
        MediaPlayer mp = new MediaPlayer(media);

        Button play = new Button("播放");

        root.getChildren().addAll(play);
        AnchorPane.setLeftAnchor(play, 100d);

        play.setOnAction(event -> mp.play());

        //构建系统托盘图标
        BufferedImage image = ImageIO.read(Objects.requireNonNull(this.getClass().getClassLoader().getResource("images/3.png")));
        TrayIcon ti = new TrayIcon(image, "javafx");
        ti.setImageAutoSize(true);

        //获取系统托盘
        SystemTray tray = SystemTray.getSystemTray();
        // 添加托盘图标
        tray.add(ti);

        // 添加鼠标事件
        ti.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                //双击左键
                if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
                    Platform.runLater(() -> {
                        if (primaryStage.isIconified()) {
                            primaryStage.setIconified(false);
                        }
                        if (!primaryStage.isShowing()) {
                            primaryStage.show();
                        }
                        primaryStage.toFront();
                    });
                }
                //鼠标右键,关闭应用
                else if (e.getButton() == MouseEvent.BUTTON3) {
                    tray.remove(ti);
                    Platform.runLater(primaryStage::close);
                    Platform.exit();
                }
            }
        });
    }
}
